<?php

namespace App\HttpController\Applet\Bingbing;

use App\HttpController\BaseController;
use App\Utility\Cache;
use App\Utility\MiniProgram;
use Carbon\Carbon;
use EasySwoole\EasySwoole\Logger;

class AuthController extends BaseController
{

    protected $applet = 'bingbing';
    protected $cacheTime = 30;
    public function login(){
        $request = $this->request();
        $code = $request->getRequestParam('code');
        $mini = new MiniProgram($this->applet);
        $session = $mini->session($code);
        if($session && isset($session['openid'])){
            //异步队列处理用户数据
            $queue = new Cache();
            $queue->onQueue('user_login');
            $queue->push(['openid'=>$session['openid'],'name'=>$this->applet]);
            //统计登录数据
            unset($queue);
            return $this->writeJson(0,$session);
        }
        //登录失败
        return $this->writeJson(1,null,'error');
    }

    /**
     * 更新用户信息
     */
    public function updateUserInfo(){
        $request = $this->request();
        $params = $request->getRequestParam();
        if(!$params['openid']){
            return $this->writeJson(1,null,'error:参数错误！');
        }
        $userModelName = $this->appletUserModel($this->applet);
        $userModel = new $userModelName;
        $userInfo = $userModel->where('openid',$params['openid'])->first();
        if(!$userInfo){
            $params['reg_at'] = Carbon::now();
            $params['login_at'] = $params['reg_at'];
            $userModel->create();
        }else{
            $params['id'] = $userInfo['id'];
            $userModel->update($params);
        }
        return $this->writeJson(0);
    }
}
